const { $Toast } = require('../dist/base/index');
// pages/index/index.js
const utils = require('../../utils/util.js')
const MD5 = require('../../utils/md5.js')
const gd = getApp().globalData;
const getStorage = utils.wxPromisify(wx.getStorage)
const setStorage = utils.wxPromisify(wx.setStorage)
const request = utils.wxPromisify(wx.request)
//获取文件管理器
var fs = wx.getFileSystemManager();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    area: {},
    itemNum: '',
    mapjson: [],
    currentIndex: 0,
    grids: [],
    imageWidth: wx.getSystemInfoSync().windowWidth, //图片宽度
    ellipsis: true, // 文字是否收起，默认收起
    hiddenmodalput: false, //可以通过hidden是否掩藏弹出框的属性，来指定那个弹出框  
    current: 'index',
    visible: false, //需要支付页面
    action: [{
        name: '微信支付',
        color: '#19be6b'
      },
      {
        name: '取消'
      }
    ],
    openid:''
  },
  /**
   * 扫描二维码函数
   */
  saoInfo: function() {
    let timesafter = this.data.area.timesafter
    if (timesafter > 0 || this.data.isPayed || this.data.area.pay == 0) {
      //调用扫码
      wx.scanCode({
        //成功回调
        success: (res) => {
          this.matcthResult('from_old_url', res.result)
        }
      })
    } else {
      //支付弹窗
      this.setData({
        visible: true, //需要支付页面
      })
    }
  },
  /**
   * 解析映射
   */
  matcthResult: function(eqcol, eqlstr) {
   
    const museum = this.data.area.museum
    const mapjson = this.data.mapjson
    const info = utils.findEqual(mapjson, eqcol, eqlstr)
    if (info) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.setStorage({
        key: 'show',
        data: {
          toNum: info.exhibit_id,
          areaNum: this.data.area.museum,
          picsNum: info.pics_number,
          exhibitName: info.exhibit_name,
          videoNum: info.video_number,
          audioNum: info.audio_number
        }
      })
      this.setData({
        hiddenmodalput: false,
        exhibition: ''
      })
      wx.navigateTo({
        url: '/pages/show/show'
      })
      let timesafter = this.data.area.timesafter
      this.data.area.timesafter = --timesafter;
      setStorage({
        key: 'area',
        data: this.data.area
      })

    } else {
      wx.showToast({
        title: '资源未找到',
        icon: 'none',
        duration: 1000
      })
      //重置输入框
      this.setData({
        exhibition: ''
      })
    }

  },
  /**
   * 提交展品编号
   */
  itemSubmit: function() {
    let itemNum = this.data.exhibition
    console.log(itemNum)
    if (!itemNum || itemNum == '') {
      this.setData({
        exhibition: ''
      })
      wx.showToast({
        title: '请求编号错误',
        icon: 'none',
        duration: 1000
      })
      return
    }
    this.matcthResult('from_old_id', itemNum)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.readMuseumInfo()
    this.readExhibitsMap()
  },
  /**
   * 读取展馆信息
   */
  readMuseumInfo: function() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const that = this
    getStorage({
      key: 'area'
    }).then(res => {
      const museum = res.data.museum
      that.setSwiperPic(gd.domain, museum, res.data.pics_number) //设置首页轮播图
      wx.setNavigationBarTitle({
        title: res.data.museum_name, //这里展馆名错误
      })
      const pavilion_info = wx.getStorageSync('pavilion_info')
      //判断是否已经请求过数据了
      if (pavilion_info) {
        //获取存储的文本数据
        that.setData({
          pavilion_info
        })
      } else {
        //如果没请求过，请求数据并存入本地
        request({
          url: `${gd.domain}sucai/${museum}/txt/0.txt`
        }).then(res => {
          const tmpdata = utils.getHilightStrArray(res.data.replace(/[\r\n]/g, ""), '####')
          setStorage({
            key: 'pavilion_info',
            data: tmpdata
          })
          that.setData({
            pavilion_info: tmpdata
          })
        })
      }
      //读取信息存入data以便使用
      that.setData({
        area: res.data
      })
      this.readFileUserVisitNum();  //判断是否已经支付过该展馆

      //读取用户是否开通过该博物馆的服务
      this.readFileUserVisitNum()
      
      //调用控制组件实现与隐藏的函数
      that.showHideCom(res.data.show_hide)
      wx.hideLoading()
    }, err => { //失败
      wx.reLaunch({
        url: '/pages/area/area',
      })
    })
  },
  /**
   * 读取展品映射表
   */
  readExhibitsMap: function() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const that = this
    getStorage({
      key: 'mapjson'
    }).then(res => {
      //读取成功存入data
      that.setData({
        mapjson: res.data
      })
    }, err => {
      //未读取到本地存储数据则请求远端Excel表获取数据并保存的本地
      const museum = that.data.area.museum
      const url = gd.domain + gd.respre + museum + '/' + gd.mappre + museum + '.xls'
      //将请求的Excel读取成json
      utils.requestExcelToJson(url).then(res => {
        setStorage({
          key: 'mapjson',
          data: res
        })
        that.setData({
          mapjson: res
        })

        wx.hideLoading()

      }, err => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 1000
        })
      })
    })
  },
  /**
   * 控制显示与隐藏组件
   */
  showHideCom: function(codestr) {
    const that = this
    //初始化按钮数据
    const numobj = {
      id: 1,
      title: '编号',
      image: 'input.png',
      event: 'modalinput'
    }
    const saomaobj = {
      id: 2,
      title: '扫码',
      image: 'saoma.png',
      event: 'saoInfo'
    }
    const searchobj = {
      id: 3,
      title: '名称',
      image: 'search.png',
      event: 'toSearch'
    }
    const tempgrids = []
    //动态加载主页图标
    if (codestr == '001') {
      tempgrids.push(searchobj)
      that.setData({
        grids: tempgrids
      })
    } else if (codestr == '010') {
      tempgrids.push(saomaobj)
      that.setData({
        grids: tempgrids
      })
    } else if (codestr == '011') {
      tempgrids.push(saomaobj)
      tempgrids.push(searchobj)
      that.setData({
        grids: tempgrids
      })
    } else if (codestr == '100') {
      tempgrids.push(numobj)
      that.setData({
        grids: tempgrids
      })
    } else if (codestr == '101') {
      tempgrids.push(numobj)
      tempgrids.push(searchobj)
      that.setData({
        grids: tempgrids
      })
    } else if (codestr == '110') {
      tempgrids.push(numobj)
      tempgrids.push(saomaobj)
      that.setData({
        grids: tempgrids
      })
    } else if (codestr == '111') {
      tempgrids.push(numobj)
      tempgrids.push(saomaobj)
      tempgrids.push(searchobj)
      that.setData({
        grids: tempgrids
      })
    }
  },

  /*
   *将轮播图的数据地址传入data
   *@param domian 域名的根路径/we_title
   *@param pavilionNum 展馆号
   *@param picNum 图片数量
   */
  setSwiperPic: function(domain, pavilionNum, picNum) {
    let temp = [];
    for (let i = 0; i < picNum; i++) {
      temp = [...temp, i];
    }
    var swiper_pics = temp.map((item) => {
      return `${domain}sucai/${pavilionNum}/pic/0_${item + 1}.jpg`
    })
    this.setData({
      swiper_pics
    })
  },
  /**
   * 收起/展开
   */
  ellipsis: function() {
    var value = !this.data.ellipsis;
    this.setData({
      ellipsis: value
    })
  },
  handleChange: function(e) {
    this.setData({
      currentIndex: e.detail.current
    })

  },
  //前往Search页面
  toSearch: function() {
    if (!this.data.isPayed && this.data.area.pay * 100 != 0) {
      //支付弹窗
      this.setData({
        visible: true, //需要支付页面
      })
    } else {
      wx.navigateTo({
        url: '../search/search',
      })
    }
  },

  //底部导航栏
  handleChange_nav({
    detail
  }) {
    if (detail.key != 'index') {
      wx.reLaunch({
        url: `/pages/${detail.key}/${detail.key}`,
      })
    }
  },

  //弹出框事件
  modalinput: function() {
    let timesafter = this.data.area.timesafter
    if (timesafter > 0 || this.data.isPayed || this.data.area.pay == 0) {
      this.setData({
        hiddenmodalput: !this.data.hiddenmodalput,
      })
    } else {
      //支付弹窗
      this.setData({
        visible: true, //需要支付页面
      })
    }
  },
  //取消按钮  
  cancel: function() {
    console.log('用户点击取消')
    this.setData({
      hiddenmodalput: false,
      exhibition: ''
    });
  },
  //确认  
  confirm: function() {
    console.log('确认')
    console.log(this.data.exhibition)
    this.itemSubmit()
  },

  //input事件
  forName: function(e) {
    this.setData({
      exhibition: e.detail.value
    })
  },
  getHilightStrArray: function(str, key) {
    return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
  },

  //微信支付事件
  handleClick({
    detail
  }) {
    const index = detail.index;
    if (index === 0) {
      //支付
      this.getUserOpenIdToPay();
    } 

    this.setData({
      visible: false
    });
  },

  //获取用户信息openid和与支付信息
  getUserOpenIdToPay() {
    let that = this;
    const { openidapi, appid, secret} = gd
    const login = utils.wxPromisify(wx.login)
    const request = utils.wxPromisify(wx.request)
    login({
      timeout: 3000,
    }).then(res => {
      const code = res.code
      request({
        url: `${openidapi}?appid=${appid}&secret=${secret}
&jsCode=${code}`,//secret不正确
      }).then(res => {
        console.log(res)
        that.setData({
          openid:res.data.openid
        })
        //调用微信预支付接口函数
        //在回调中，在添加支付
        that.userPay()
      })
    },err => {
      consol.log("用户openid获取失败") 
    })
  },

  //支付业务
  userPay(){
    let that = this
    let museum = this.data.area.museum
    let newPay = this.data.area.pay * 100
    //记录用户支付过博物馆的文件目录
    const payHistory = `${wx.env.USER_DATA_PATH}/${museum}.txt`;
    utils.generatePreOrder(this.data.openid, newPay, res => {
      const { appid, nonceStr, prepay_id,key} = res
      const timeStamp = Date.now().toString()
      const paySign = MD5.hash(`appId=${appid}&nonceStr=${nonceStr}&package=prepay_id=${prepay_id}&signType=MD5&timeStamp=${timeStamp}&key=${key}`).toUpperCase()
      console.log(paySign)
      wx.requestPayment({
        timeStamp,
        nonceStr,
        package : 'prepay_id=' + prepay_id,
        paySign,
        signType:'MD5',
        success(res) {
          fs.writeFileSync(payHistory, " ", "utf-8");
          that.setData({
            isPayed: true
          })
          //用户支付成功
          wx.showToast({
            title: '服务已开通，请稍等',
            icon: "none",
            mask: true,
            duration: 5000,
          })
        },
        fail(res) {
          // fs.writeFileSync(payHistory, " ", "utf-8");
          // that.setData({
          //   isPayed: true
          // })
          //用户支付失败
          console.log(res)
          $Toast({
            content: '支付失败',
            type: 'error'
          });
        }
      })
    })
    
  },

  //记录用户支付过的记录
  readFileUserVisitNum: function () {
    let that = this
    let museum = this.data.area.museum
    //记录用户支付过博物馆的文件目录
    const payHistory = `${wx.env.USER_DATA_PATH}/${museum}.txt`;
    console.log(payHistory)
    fs.access({
      path: payHistory,
      success() {
        that.setData({
          isPayed:true
        })
      },
      fail(res) {
        console.log(res)
        that.setData({
          isPayed: false
        })
        // fs.writeFileSync(payHistory, " ", "utf-8");
      }
    })
  }
})